<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
// 组件
import { ElMessage } from 'element-plus'
// 接口
import type { IMenuFormData, IMenuData } from '@/api/system/menu/type'
import type { ResponseData } from '@/types/common'
import type { FormRules, FormInstance } from 'element-plus'
// api
import { reqMenuAdd, reqMenuEdit } from '@/api/system/menu/index'
// 组件参数
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
})
// 组件事件
const emit = defineEmits(['update:modelValue', 'refresh-list'])
// 计算数据
const visible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})
// 表单参数
let form = reactive<IMenuFormData>({
  name: '',
  code: '',
  type: 1,
  level: 0,
  pid: 0,
})
// 表单
const formRef = ref<FormInstance>()
const rules = reactive<FormRules<IMenuFormData>>({
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入资源编码', trigger: 'blur' }],
})

// 弹窗关闭
const close = () => {
  // 重置表单
  formRef.value?.resetFields()
}
// 点击取消
const handleCancel = () => {
  visible.value = false
}
// 点击确认
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const { code, message }: ResponseData = await (form.id
        ? reqMenuEdit(form)
        : reqMenuAdd(form))
      if (code === 200) {
        ElMessage({
          message: message,
          type: 'success',
        })
        visible.value = false
        emit('refresh-list')
      } else {
        ElMessage({
          message: message,
          type: 'error',
        })
        emit('refresh-list')
      }
    }
  })
}

// 表单初始化
const setFormData = (row: IMenuData, isEdit: number | boolean) => {
  const { id, name, code, level, pid, type } = row
  if (isEdit) {
    // 修改菜单
    form = reactive<IMenuFormData>({
      id,
      name,
      code,
      level,
      pid,
      type,
    })
  } else {
    // 新增子菜单
    form = reactive<IMenuFormData>({
      name: '',
      code: '',
      type: 1,
      level: level + 1,
      pid: id,
    })
  }
}
// 子组件暴露方法
defineExpose({ setFormData })
</script>
<template>
  <el-dialog
    v-model="visible"
    :title="form.id ? '编辑' : '新增'"
    width="500"
    @close="close"
  >
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入菜单名称" clearable />
      </el-form-item>
      <el-form-item label="资源编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入资源编码" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
